package com.solo.system.service.impl;

import com.solo.common.core.base.service.impl.BasicServiceImpl;
import com.solo.common.core.utils.collection.CollUtils;
import com.solo.system.api.entity.SysNoticeUser;
import com.solo.system.mapper.SysNoticeUserMapper;
import com.solo.system.model.notice.SysNoticeUserConvert;
import com.solo.system.service.SysNoticeUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Set;

/**
 * 通知公告用户关联 Service实现类
 * @author 十一
 * @since 2024-12-04 14:28
 * 人生若只如初见，何事秋风悲画扇
 **/
@Service
@RequiredArgsConstructor
public class SysNoticeUserServiceImpl extends BasicServiceImpl<SysNoticeUserMapper, SysNoticeUser> implements SysNoticeUserService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatch(Collection<Long> receivers, Long noticeId) {
        // 获取所有可查看该通知公告的用户id集合
        Set<Long> dbUserIds = CollUtils.toSet(mapper.selectUserIdsByNoticeId(noticeId));
        // 计算删除和新增的用户编号
        Collection<Long> deleteUserIds = CollUtils.subtract(dbUserIds, receivers);
        Collection<Long> createUserIds = CollUtils.subtract(receivers, dbUserIds);
        // 删除取消的用户
        if(CollUtils.isNotEmpty(deleteUserIds)) {
            mapper.deleteByNoticeIdAndUserIds(noticeId, deleteUserIds);
        }
        // 增加新增的用户
        if(CollUtils.isNotEmpty(createUserIds)) {
            saveBatch(SysNoticeUserConvert.INSTANCE.convert(createUserIds, noticeId));
        }
        return Boolean.TRUE;
    }

}
